<template>
  <el-dialog
    v-model="visible"
    title="Tips"
    width="800"
    class="assistant-dialog"
    :before-close="handleClose"
  >
    <template #title>
      <div class="header">
        <el-image :src="logo" lazy loading="lazy"></el-image>
        <div class="title-box">
          <div>聊天配置</div>
          <div>为你的知识库配置专属聊天助手！ 💕</div>
        </div>
      </div>
    </template>
    <el-divider />
    <el-radio-group v-model="activeName" size="large" class="radio-group">
      <el-radio-button label="助理设置" value="assistantSettings" />
      <el-radio-button label="提示引擎" value="promptEngine" />
      <el-radio-button label="模型设置" value="modelSettings" />
    </el-radio-group>
    <div class="main">
      <!-- <AssistantSettings
        v-if="activeName === 'assistantSettings'"
        ref="assistantRef"
      >
      </AssistantSettings>
      <PromptEngine v-if="activeName === 'promptEngine'" ref="engineRef">
      </PromptEngine>
      <ModelSettings v-if="activeName === 'modelSettings'" ref="modelRef">
      </ModelSettings> -->
      <AssistantSettings
        ref="assistantRef"
        :activeName="activeName"
        v-model="form.assistantForm"
      >
      </AssistantSettings>
      <PromptEngine
        ref="engineRef"
        :activeName="activeName"
        v-model="form.engineForm"
      >
      </PromptEngine>
      <ModelSettings
        ref="modelRef"
        :activeName="activeName"
        v-model="form.modelForm"
      >
      </ModelSettings>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSure"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";
import AssistantSettings from "./assistant-settings.vue";
import PromptEngine from "./prompt-engine.vue";
import ModelSettings from "./model-settings.vue";
import logo from "@/assets/images/loginLogo.png";
import {
  assistantCreateApi,
  assistantUpdateApi,
} from "@/api/knowledge/chat.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  assistantData: {
    type: Object,
    default: () => {},
  },
  addEdit: {
    type: String,
    default: "add",
  },
});

const activeName = ref("assistantSettings");
const assistantRef = ref(null);
const engineRef = ref(null);
const modelRef = ref(null);
const formInit = {
  // 助理设置
  assistantForm: {
    name: "", // 助理姓名
    description: "", // 助理描述
    avatar: "", // 助理头像
    empty_response: "", // 空回复
    prologue: "", // 设置开场白
    quote: false, // 显示引文
    // keyword: false, // 关键词分析
    tts: false, // 文本转语音
    // tavily: "", // Tavily API Key
    dataset_ids: [], // 知识库
    avatarFile: null,
  },
  // 提示引擎
  engineForm: {
    system:
      "你是一个智能助手，请总结知识库的内容来回答问题，请列举知识库中的数据详细回答，请务必回答完整。当所有知识库内容都与问题无关时，你的回答必须包括“知识库中未找到您要的答案！”这句话。回答需要考虑聊天历史。以下是知识库：{knowledge} 以上是知识库。", // 系统提示词
    similarity_threshold: 0.0, // 相似度阈值
    keywords_similarity_weight: 0.0, // 关键字相似度权重
    top_n: 0, // Top N
    refine_multiturn: false, // 多轮对话优化
    // useKnowledgeGraph: false, // 使用知识图谱
    // reasoning: false, // 推理
    // rerank_model: "", // rerank模型
    variables: [], // 变量list
  },
  // 模型设置
  modelForm: {
    // model_name: "", // 模型
    freedom: "Precise", // 自由度
    temperature_enabled: true, // 温度开关
    temperature: 0.0, // 温度滑块
    top_p_enabled: true, // Top P开关
    top_p: 0.0, // Top P滑块
    presence_penalty_enabled: true, // 存在处罚开关
    presence_penalty: 0.0, // 存在处罚滑块
    frequency_penalty_enabled: true, // 频率惩罚开关
    frequency_penalty: 0.0, // 频率惩罚滑块
  },
};
let form = reactive({
  ...formInit,
});
let paramsForm = ref(); // 提交表单

const emits = defineEmits(["update:modelValue", "confirm"]);
const visible = computed({
  get() {
    return props.modelValue;
  },
  set() {
    handleClose();
  },
});

watch(
  visible,
  (newVal) => {
    if (props.addEdit === "add") {
      Object.assign(form, { ...form, ...formInit });
    } else if (props.addEdit === "edit") {
      const assistantData = cloneDeep(props.assistantData);
      const { prompt, llm } = assistantData;
      form.assistantForm = {
        ...form.assistantForm,
        name: assistantData.name, // 助理姓名
        description: assistantData.description, // 助理描述
        avatar: assistantData.avatar, // 助理头像
        empty_response: prompt.empty_response, // 空回复
        prologue: "", // 设置开场白
        quote: false, // 显示引文
        tts: false, // 文本转语音
        dataset_ids: [], // 知识库
        avatarFile: null,
      };
      form.engineForm = {
        system: "", // 系统提示词
        similarity_threshold: prompt.similarity_threshold, // 相似度阈值
        keywords_similarity_weight: prompt.keywords_similarity_weight, // 关键字相似度权重
        top_n: prompt.top_n, // Top N
        refine_multiturn: false, // 多轮对话优化
        variables: prompt.variables, // 变量list
      };
      form.modelForm = {
        freedom: "Precise", // 自由度
        temperature_enabled:
          llm?.temperature || llm?.temperature === 0 ? true : false, // 温度开关
        temperature: llm?.temperature, // 温度滑块
        top_p_enabled: llm?.top_p || llm?.top_p === 0 ? true : false, // Top P开关
        top_p: llm?.top_p, // Top P滑块
        presence_penalty_enabled:
          llm?.presence_penalty || llm?.presence_penalty === 0 ? true : false, // 存在处罚开关
        presence_penalty: llm?.presence_penalty, // 存在处罚滑块
        frequency_penalty_enabled:
          llm?.frequency_penalty || llm?.frequency_penalty === 0 ? true : false, // 频率惩罚开关
        frequency_penalty: llm?.frequency_penalty, // 频率惩罚滑块
      };
    }
  },
  {
    deep: true,
  }
);

const handleClose = () => {
  emits("update:modelValue", false);
};

// 新建助理
const createAssistant = async () => {
  const { code } = await assistantCreateApi(paramsForm.value);
  if (code === 200) {
    ElMessage({
      type: "success",
      message: "新建助理成功",
    });
    emits("confirm", "add");
    handleClose();
  }
};

// 更新助理
const updateAssistant = async () => {
  const params = {
    ...paramsForm.value,
    chat_id: props.assistantData.id,
  };
  const { code } = await assistantUpdateApi(params);
  if (code === 200) {
    ElMessage({
      type: "success",
      message: "编辑成功",
    });
    emits("confirm", "edit");
    handleClose();
  }
};

const handleSure = async () => {
  const assistantForm = assistantRef.value.$refs.formRef;
  const engineForm = engineRef.value.$refs.formRef;
  try {
    // 校验所有表单
    const results = await Promise.all([
      assistantForm?.validate().catch((err) => err),
      engineForm?.validate().catch((err) => err),
    ]);

    // 检查是否有验证错误
    const hasError = results.some((result) => result !== true);
    if (hasError) {
      ElMessage.error("请检查所有表单的填写是否正确");
      return;
    }

    // 所有表单验证通过
    ElMessage.success("所有表单验证通过");
    // console.log("表单数据", form);

    const {
      name,
      description,
      avatar,
      empty_response,
      prologue,
      quote,
      tts,
      dataset_ids,
    } = form.assistantForm;
    const {
      system,
      similarity_threshold,
      keywords_similarity_weight,
      top_n,
      refine_multiturn,
      variables,
    } = form.engineForm;
    const {
      temperature_enabled,
      temperature,
      top_p_enabled,
      top_p,
      presence_penalty_enabled,
      presence_penalty,
      frequency_penalty_enabled,
      frequency_penalty,
    } = form.modelForm;

    // 处理传参数据结构
    paramsForm.value = {
      name,
      description,
      avatar,
      dataset_ids,
      prompt: {
        empty_response,
        similarity_threshold,
        keywords_similarity_weight,
        top_n,
        variables,
      },
      prompt_config: {
        prologue,
        quote,
        tts,
        system,
        refine_multiturn,
      },
      llm: {
        temperature,
        top_p,
        presence_penalty,
        frequency_penalty,
      },
    };
    !temperature_enabled && delete paramsForm.value.llm.temperature;
    !top_p_enabled && delete paramsForm.value.llm.top_p;
    !presence_penalty_enabled && delete paramsForm.value.llm.presence_penalty;
    !frequency_penalty_enabled && delete paramsForm.value.llm.frequency_penalty;

    // 这里可以添加提交逻辑
    if (props.addEdit === "add") {
      createAssistant();
    } else if (props.addEdit === "edit") {
      updateAssistant();
    }
  } catch (error) {
    console.error("验证出错:", error);
  }
};
</script>

<style lang='scss' scoped>
.header {
  display: flex;
  align-items: center;
  .el-image {
    width: 70px;
    margin-right: 10px;
  }
}
.el-divider--horizontal {
  margin: 0 0 20px 0;
}

.radio-group {
  display: flex;
  justify-content: center;
}

.main {
  margin: 20px;
}
</style>
<style>
.assistant-dialog {
  margin: 50px auto;
}
</style>